# encoding: utf-8
'''
Created: 2014-04-28 12:48

@author: VAN
'''
import os
import re
import urllib2


def checkfile(filename):
    return os.path.exists(filename)

def similerjsonstr2dict(strval):
    return eval(strval.replace('{', 'dict(').replace('}', ')').replace(':', '='))

def extractjson(rsp, regex):
    pattern = re.compile(regex);
    match = pattern.match(rsp);
    ret = '';
    if match:
        ret = match.group(1);
    return ret;

def lrc_download_handler(lrc_down_url, iid):
    if len(lrc_down_url) > 0:
        filename = 'D:/Users/usr/Desktop/crawler/lrc/' + str(iid) + ".lrc"
        if checkfile(filename) == True:
            return True
        rsp = urllib2.urlopen(lrc_down_url)
        html = rsp.read();
        f = open (filename, "w");
        f.writelines(html);
        f.close();
        return True
    else:
        return False;
    
def lrc2diskhandler(content, iid):
    if len(content) > 0:
        filename = 'D:/Users/usr/Desktop/crawler/lrc/' + str(iid) + ".lrc"
        if checkfile(filename) == True:
            return True
        f = open (filename, "w")
        f.writelines(content)
        f.close();
        return True
    else:
        return False;
    
def mp3_download_handler(mp3_download_url, iid):
    if len(mp3_download_url) > 0:
        filename = 'D:/Users/usr/Desktop/crawler/mp3/' + str(iid) + ".mp3";
        if checkfile(filename) == True:
            return True;
        req = urllib2.Request(url=mp3_download_url)
        f = urllib2.urlopen(req)
        with open(filename, "wb") as code:
            code.write(f.read())
        return True
    else:
        return False
